Understanding Secure Data

Provides a secure wrapper around sensitive string data, using byte arrays and constant-time comparison to prevent memory leaks and timing attacks. Supports secure conversion from and to strings, with explicit clearing of sensitive data in memory.

Types

SecureData

A readonly struct that holds sensitive byte data and provides secure conversions, disposal, and constant-time equality.

  • Fields:

    • byte[] _bytes: Internal byte buffer holding the data.
  • Methods:

    • byte[] ConvertToBytes(): Returns a copy of the byte array.
    • string ConvertToString(): Converts the data back to a UTF-8 string.
    • static SecureData FromString(string value): Creates a SecureData instance from a string and clears the original.
    • override string ToString(): Returns a base64 representation of the internal data.
    • void Dispose(): Clears the internal byte array from memory.
    • static bool operator (SecureData left, SecureData right): Performs a constant-time comparison.
    • static bool operator !=(SecureData left, SecureData right): Negation of the == operator.
    • override bool Equals(object? obj): Checks for equality with another SecureData.
    • override int GetHashCode(): Returns a hash code based on data length.
    • bool SecureCompare(SecureData other): Compares contents in constant time.

(TL;DR? Doing any equality check on SecureDatas automatically overrides the default system way with a more secure version. Use plainPassword.ToSecureData() to get a SecureData object from a string, then use securePassword.ConvertToString() to get the original string back. You should be able to use the BinaryConverter to format any item to bytes, then encode it with UTF8 into a string before turning it into SecureData. It's reccomended to do this with smaller variables instead of large ones. However, if you need larger variables to be saved like this, remember to use async/threading principles to ensure you don't accidently freeze your program.)


SecureDataExtensions

Provides extension methods for safely converting and clearing sensitive string data.

  • Methods:
    • SecureData ToSecureData(this string value): Converts a string to SecureData and securely clears the original.
    • void SecureClear(this string value): Overwrites a string’s contents in memory with null characters, unless it’s interned.

Interned Example - string interned = "sensitive";
Non Interned Example - string nonInterned = new string("sensitive".ToCharArray());